package com.wn.ticket.security.backstage;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @author wuqingting
 * @date 2022/8/22
 */
public class BackstageAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
    protected BackstageAuthenticationFilter(String defaultFilterProcessesUrl) {//指定过滤器需要处理的路径
        super(defaultFilterProcessesUrl);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String,String> map = objectMapper.readValue(request.getInputStream(), Map.class);
        String account=map.get("account");
        String password=map.get("password");
        UsernamePasswordAuthenticationToken authenticationToken = UsernamePasswordAuthenticationToken.unauthenticated(account, password);

        return this.getAuthenticationManager().authenticate(authenticationToken);
    }
}
